package com.phospherus.flow.service

import com.phospherus.flow.entity.*
import com.phospherus.flow.repository.*
import org.apache.commons.lang.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * 流程1表单数据
 * @author songjinlong
 * @version 1.0
 * @since 2017/12/21
 */
@Service
class BusinessLadingService : FormInstBaseService() {
    @Autowired
    lateinit var businessAuditRepository: BusinessAuditRepository
    @Autowired
    lateinit var foreignTradeContractRepository: ForeignTradeContractRepository
    @Autowired
    lateinit var ftcProductDetailsRepository: FtcProductDetailsRepository
    @Autowired
    lateinit var pIRepository: PIRepository
    @Autowired
    lateinit var priceInformationRepository: PriceInformationRepository
    @Autowired
    lateinit var domesticTradeContractRepository: DomesticTradeContractRepository
    @Autowired
    lateinit var dtcGoodsPriceRepository: DtcGoodsPriceRepository
    @Autowired
    lateinit var profitCalculationRepository: ProfitCalculationRepository
    @Autowired
    lateinit var pcOrderInfoRepository: PcOrderInfoRepository
    @Autowired
    lateinit var businessAuditTablesRepository: BusinessAuditTablesRepository

    @Autowired
    lateinit var depositPayRepository: DepositPayRepository
    @Autowired
    lateinit var dpPriceInformationRepository: DpPriceInformationRepository


    @Autowired
    lateinit var paymentNoticeRepository: PaymentNoticeRepository
    @Autowired
    lateinit var pnGoodDetailRepository: PnGoodDetailRepository


    override fun getFormInstServiceName(): String = "business_lading"

    override fun query(formInstId: Long): MutableMap<String, Any?>? {
        var map = mutableMapOf<String, Any?>()
        //业务审核单
        var bussinessAudit = businessAuditRepository.findByFormInstId(formInstId)
        bussinessAudit.attachedFileList = attachedFileService.getFormAttachedFiles(formInstId, bussinessAudit.id, "businessform_businesscheckform")
        bussinessAudit.bb_table1 = businessAuditTablesRepository.findByFormInstIdAndBaId(formInstId, bussinessAudit.id!!)
        map["businessform_businesscheckform"] = bussinessAudit

        //外贸合同
        var foreignTradeContract = foreignTradeContractRepository.findByFormInstId(formInstId)
        foreignTradeContract.bf_table1 = ftcProductDetailsRepository.findByFormInstIdAndFtcId(formInstId, foreignTradeContract.id!!)
        foreignTradeContract.attachedFileList = attachedFileService.getFormAttachedFiles(formInstId, foreignTradeContract.id, "businessform_foreigntradecontract")
        map["businessform_foreigntradecontract"] = foreignTradeContract

        //PI
        var pi = pIRepository.findByFormInstId(formInstId)
        pi.bp_table1 = priceInformationRepository.findByFormInstIdAndPiId(formInstId, pi.id!!)
        pi.attachedFileList = attachedFileService.getFormAttachedFiles(formInstId, pi.id, "businessform_pi")
        map["businessform_pi"] = pi

        //内贸合同
        var domesticTradeContractList = domesticTradeContractRepository.findByFormInstId(formInstId)
        domesticTradeContractList.forEach {
            it.bd_table1 = dtcGoodsPriceRepository.findByFormInstIdAndDtcId(formInstId, it.id!!)
            it.attachedFileList = attachedFileService.getFormAttachedFiles(formInstId, it.id, "businessform_domestictradecontract")
        }
        map["businessform_domestictradecontract"] = domesticTradeContractList

        //业务利润测算表
        var profitCalculation = profitCalculationRepository.findByFormInstId(formInstId)
        profitCalculation.bpc_table1 = pcOrderInfoRepository.findByFormInstIdAndPcId(formInstId, profitCalculation.id!!)
        profitCalculation.attachedFileList = attachedFileService.getFormAttachedFiles(formInstId, profitCalculation.id, "businessform_profitcalculation")
        map["businessform_profitcalculation"] = profitCalculation

        //保证金付款发票
        var depositPay = depositPayRepository.findByFormInstId(formInstId)
        depositPay.bdp_table1 = dpPriceInformationRepository.findByFormInstIdAndDpId(formInstId, depositPay.id!!)
        depositPay.attachedFileList = attachedFileService.getFormAttachedFiles(formInstId, depositPay.id, "businessform_depositpay")
        map["businessform_depositpay"] = depositPay

        //付款通知
        var paymentNotice = paymentNoticeRepository.findByFormInstId(formInstId)
        paymentNotice.bpn_table1 = pnGoodDetailRepository.findByFormInstIdAndPnId(formInstId, paymentNotice.id!!)
        paymentNotice.attachedFileList = attachedFileService.getFormAttachedFiles(formInstId, paymentNotice.id, "businessform_paymentnotice")
        map["businessform_paymentnotice"] = paymentNotice

        return map
    }

    override fun save(map: MutableMap<String, Any>) {
        var formInstId = map["formInstId"] as Long
        //业务审核单
        var businessAuditMap = map["businessform_businesscheckform"] as Map<String, Any>?
        if (businessAuditMap != null) {
            var businessAudit = createEntityByMap<BusinessAudit>(businessAuditMap, BusinessAudit::class.java)
            businessAudit.formInstId = formInstId
            businessAudit = businessAuditRepository.save(businessAudit)
            if (StringUtils.isNotBlank(businessAuditMap["attachedFiles"] as? String )) {
                attachedFileService.addFormInstAttachedFile(businessAuditMap["attachedFiles"].toString(), formInstId, "businessform_businesscheckform", businessAudit.id)
            }
            var businessAuditTablesList = businessAuditMap["bb_table1"] as List<Map<String, Any>>?
            var businessAuditTables: List<BusinessAuditTables>? = null
            if (businessAuditTablesList != null) {
                businessAuditTables = businessAuditTablesList.mapTo(ArrayList(), {
                    with(createEntityByMap<BusinessAuditTables>(it, BusinessAuditTables::class.java)) {
                        this.id = null
                        this.formInstId = formInstId
                        this.baId = businessAudit.id
                        this
                    }
                })
            }
            var tables = businessAuditTablesRepository.findByFormInstIdAndBaId(formInstId, businessAudit.id!!)
            businessAuditTablesRepository.delete(tables)
            if(businessAuditTables != null){
                businessAuditTablesRepository.save(businessAuditTables)
            }

        }

        //外贸合同
        var foreignTradeContractMap = map["businessform_foreigntradecontract"] as Map<String, Any>?
        if (foreignTradeContractMap != null) {
            var foreignTradeContract = createEntityByMap<ForeignTradeContract>(foreignTradeContractMap, ForeignTradeContract::class.java)
            foreignTradeContract.formInstId = formInstId
            foreignTradeContract = foreignTradeContractRepository.save(foreignTradeContract)
            if (StringUtils.isNotBlank(foreignTradeContractMap["attachedFiles"] as? String )) {
                attachedFileService.addFormInstAttachedFile(foreignTradeContractMap["attachedFiles"].toString(), formInstId, "businessform_foreigntradecontract", foreignTradeContract.id)
            }
            var ftcProductDetailsList = foreignTradeContractMap["bf_table1"] as List<Map<String, Any>>?
            var ftcProductDetails: List<FtcProductDetails>? = null
            if (ftcProductDetailsList != null) {
                ftcProductDetails = ftcProductDetailsList.mapTo(ArrayList(), {
                    with(createEntityByMap<FtcProductDetails>(it, FtcProductDetails::class.java)) {
                        this.id = null
                        this.formInstId = formInstId
                        this.ftcId = foreignTradeContract.id
                        this
                    }
                })

            }
            var tables = ftcProductDetailsRepository.findByFormInstIdAndFtcId(formInstId, foreignTradeContract.id!!)
            ftcProductDetailsRepository.delete(tables)
            if(ftcProductDetails != null){
                ftcProductDetailsRepository.save(ftcProductDetails)
            }
        }
        //PI
        var piMap = map["businessform_pi"] as Map<String, Any>?
        if (piMap != null) {
            var pi = createEntityByMap<PI>(piMap, PI::class.java)
            pi.formInstId = formInstId
            pi = pIRepository.save(pi)
            if (StringUtils.isNotBlank(piMap["attachedFiles"] as? String )) {
                attachedFileService.addFormInstAttachedFile(piMap["attachedFiles"].toString(), formInstId, "businessform_pi", pi.id)
            }
            var priceInformationList = piMap["bp_table1"] as List<Map<String, Any>>?
            var priceInformations: List<PriceInformation>? = null
            if (priceInformationList != null) {
                priceInformations = priceInformationList.mapTo(ArrayList(), {
                    with(createEntityByMap<PriceInformation>(it, PriceInformation::class.java)) {
                        this.id = null
                        this.formInstId = formInstId
                        this.piId = pi.id
                        this
                    }
                })
            }
            var tables = priceInformationRepository.findByFormInstIdAndPiId(formInstId, pi.id!!)
            priceInformationRepository.delete(tables)
            if(priceInformations!=null){
                priceInformationRepository.save(priceInformations)
            }

        }

        //内贸合同
        var domesticTradeContractList = map["businessform_domestictradecontract"] as List<Map<String, Any>>?
        if (domesticTradeContractList != null) {
            domesticTradeContractList.forEach {
                var dtcMap = it
                var dtc = createEntityByMap<DomesticTradeContract>(dtcMap, DomesticTradeContract::class.java)
                dtc.formInstId = formInstId
                dtc = domesticTradeContractRepository.save(dtc)
                if (StringUtils.isNotBlank(dtcMap["attachedFiles"] as? String )) {
                    attachedFileService.addFormInstAttachedFile(dtcMap["attachedFiles"].toString(), formInstId, "businessform_domestictradecontract", dtc.id)
                }
                var dtcGoodsPriceList = dtcMap["bd_table1"] as List<Map<String, Any>>?
                var dtcGoodsPriceLists: List<DtcGoodsPrice>? = null
                if (dtcGoodsPriceList != null) {
                    dtcGoodsPriceLists = dtcGoodsPriceList.mapTo(ArrayList(), {
                        with(createEntityByMap<DtcGoodsPrice>(it, DtcGoodsPrice::class.java)) {
                            this.id = null
                            this.formInstId = formInstId
                            this.dtcId = dtc.id
                            this
                        }
                    })
                }
                var tables = dtcGoodsPriceRepository.findByFormInstIdAndDtcId(formInstId, dtc.id!!)
                dtcGoodsPriceRepository.delete(tables)
                if(dtcGoodsPriceLists!=null){
                    dtcGoodsPriceRepository.save(dtcGoodsPriceLists)
                }
            }
        }

        //业务利润测算表
        var profitCalculationMap = map["businessform_profitcalculation"] as Map<String, Any>?
        if (profitCalculationMap != null) {
            var profitCalculation = createEntityByMap<ProfitCalculation>(profitCalculationMap, ProfitCalculation::class.java)
            profitCalculation.formInstId = formInstId
            profitCalculation = profitCalculationRepository.save(profitCalculation)
            if (StringUtils.isNotBlank(profitCalculationMap["attachedFiles"] as? String )) {
                attachedFileService.addFormInstAttachedFile(profitCalculationMap["attachedFiles"].toString(), formInstId, "businessform_profitcalculation", profitCalculation.id)
            }
            //利润测算-订单详情
            var pcOrderInfoList = profitCalculationMap["bpc_table1"] as List<Map<String, Any>>?
            var pcOrderInfos: List<PcOrderInfo>? = null
            if (pcOrderInfoList != null) {
                pcOrderInfos = pcOrderInfoList.mapTo(ArrayList(), {
                    with(createEntityByMap<PcOrderInfo>(it, PcOrderInfo::class.java)) {
                        this.id = null
                        this.formInstId = formInstId
                        this.pcId = profitCalculation.id
                        this
                    }
                })
            }
            var tables = pcOrderInfoRepository.findByFormInstIdAndPcId(formInstId, profitCalculation.id!!)
            pcOrderInfoRepository.delete(tables)
            if(pcOrderInfos!=null){
                pcOrderInfoRepository.save(pcOrderInfos)
            }
        }

        //保证金付款发票
        var depositPayMap = map["businessform_depositpay"] as Map<String, Any>?
        if (depositPayMap != null) {
            var depositPay = createEntityByMap<DepositPay>(depositPayMap, DepositPay::class.java)
            depositPay.formInstId = formInstId
            depositPay = depositPayRepository.save(depositPay)
            if (StringUtils.isNotBlank(depositPayMap["attachedFiles"] as? String )) {
                attachedFileService.addFormInstAttachedFile(depositPayMap["attachedFiles"].toString(), formInstId, "businessform_depositpay", depositPay.id)
            }
            //保证金付款发票-价格信息
            var dpPriceInformationList = depositPayMap["bdp_table1"] as List<Map<String, Any>>?
            var dpPriceInformations: List<DpPriceInformation>? = null
            if (dpPriceInformationList != null) {
                dpPriceInformations = dpPriceInformationList.mapTo(ArrayList(), {
                    with(createEntityByMap<DpPriceInformation>(it, DpPriceInformation::class.java)) {
                        this.id = null
                        this.formInstId = formInstId
                        this.dpId = depositPay.id
                        this
                    }
                })
            }
            var tables = dpPriceInformationRepository.findByFormInstIdAndDpId(formInstId, depositPay.id!!)
            dpPriceInformationRepository.delete(tables)
            if(dpPriceInformations!=null){
                dpPriceInformationRepository.save(dpPriceInformations)
            }
        }

        //通知付款
        var paymentNoticeMap = map["businessform_paymentnotice"] as Map<String, Any>?
        if (paymentNoticeMap != null) {
            var paymentNotice = createEntityByMap<PaymentNotice>(paymentNoticeMap, PaymentNotice::class.java)
            paymentNotice.formInstId = formInstId
            paymentNotice = paymentNoticeRepository.save(paymentNotice)
            if (StringUtils.isNotBlank(paymentNoticeMap["attachedFiles"] as? String )) {
                attachedFileService.addFormInstAttachedFile(paymentNoticeMap["attachedFiles"].toString(), formInstId, "businessform_paymentnotice", paymentNotice.id)
            }
            //通知付款-货物详情
            var pnGoodDetailList = paymentNoticeMap["bpn_table1"] as List<Map<String, Any>>?
            var pnGoodDetails: List<PnGoodDetail>? = null
            if (pnGoodDetailList != null) {
                pnGoodDetails = pnGoodDetailList.mapTo(ArrayList(), {
                    with(createEntityByMap<PnGoodDetail>(it, PnGoodDetail::class.java)) {
                        this.id = null
                        this.formInstId = formInstId
                        this.pnId = paymentNotice.id
                        this
                    }
                })
            }
            var tables = pnGoodDetailRepository.findByFormInstIdAndPnId(formInstId, paymentNotice.id!!)
            pnGoodDetailRepository.delete(tables)
            if(pnGoodDetails!=null){
                pnGoodDetailRepository.save(pnGoodDetails)
            }
        }
    }
}
